// Main.java
public class Main {
public static void main(String[] args){
Animal dog = new Dog();
Cat cat1 = new Cat();
Animal cat2 = new Cat();
// Animal animal = new Animal(); //'Animal is abstract; cannot be instantiated
// Polymorphism => 生態多樣性的概念
// 同一個Animal物件可以有Dog,Cat...各種可能性
dog1.makeSound();
cat1.makeSound();
cat2.makeSound();
}
}
// Animal.java
public abstract class Animal {
protected String name;
protected int age;
// method overloading
public Animal(){
this.name = "A animal";
this.age = 0;
}
public Animal(String name, int age){
this.name = name;
this.age = age;
}
public void eat(){
System.out.println("Eatting...");
}
public void sleep(){
System.out.println("Sleeping...");
}
public abstract void makeSound();
}
// Cat.java
public class Cat extends Animal{
public Cat(){
super("Cat"); // super: 讓Cat(子類別)呼叫Animal(父類別)的建構子
}
@Override
public void makeSound(){
System.out.println("Meow...");
}
}
// Dog.java
public class Dog extends Animal{
public Dog(){
super("Dog");
}
@Override
public void makeSound(){
System.out.println("Bark...");
}
}
介面在Java中是一個"完全抽象類別",在介面的方法全部都是抽象方法
// Main.java
public class Main {
public static void main(String[] args){
Dog dog = new Dog();
Cat cat1 = new Cat();
// Polymorphism => 生態多樣性的概念
// 同一個Animal物件可以有Dog,Cat...各種可能性
System.out.println(dog.isMyFriend());
System.out.println(cat1.isMyFriend());
}
}
// Animal.java
public abstract class Animal {
protected String name;
protected int age;
// method overloading
public Animal(){
this.name = "A animal";
this.age = 0;
}
public Animal(String name, int age){
this.name = name;
this.age = age;
}
public void eat(){
System.out.println("Eatting...");
}
public void sleep(){
System.out.println("Sleeping...");
}
public abstract void makeSound();
}
// Cat.java
public class Cat extends Animal implements CanBeFriend {
public Cat(){
super("Cat", 3); // super: 讓Cat(子類別)呼叫Animal(父類別)的建構子
}
@Override
public void makeSound(){
System.out.println("Meow...");
}
@Override
public String isMyFriend(){
return "You are not my friend!!";
}
}
// Dog.java
public class Dog extends Animal implements CanBeFriend {
public Dog(){
super("Dog", 5);
}
@Override
public void makeSound(){
System.out.println("Bark...");
}
@Override
public String isMyFriend(){
return "You are my good friend~";
}
}
// CanBeFriend.java
public interface CanBeFriend {
// Interface default properties
// public static final
String isMyFriend();
}
兩者性質很相近,有以下幾點的不同